<template>
  <div class="container">
    <div class="page">
      <div class="bd" v-if="state.dataList && state.dataList.length > 0">
        <!-- 1是单选 2是判断 3是多选 -->
        <div>
          <div class="exam-hd">
            {{state.idx + 1}}.
            <span class="exam-hd-border" v-if="state.dataList[state.idx].answer_type === '1'">(单选题)</span>
            <span class="exam-hd-border" v-else-if="state.dataList[state.idx].answer_type === '2'">(判断题)</span>
            <span class="exam-hd-border" v-else>(多选题)</span>
            {{state.dataList[state.idx].question_title}}
          </div>
          <div class="exam-bd" v-if="state.dataList[state.idx].answersList && state.dataList[state.idx].answersList.length > 0">
            <div v-if="!state.dataList[state.idx].answer_flag">
              <div
                class="flex"
                style="padding: 10px 0 5px 0; align-items: center;"
                @click="chooseOptions(i)"
                v-for="(item, i) in state.dataList[state.idx].answersList"
                :key="i"
              >
                <span class="icon-check" :class="{'checked': isSelected(i)}"></span>
                <!-- <div class="options" :class="{'color-blue': isSelected(i)}">{{optionTitle[i]}}、{{item}}</div> -->
                <div class="options" :class="{'color-blue': isSelected(i)}">{{item}}</div>
              </div>
            </div>
            <div v-else>
              <div
                class="flex"
                style="padding: 10px 0 5px 0; align-items: center;"
                v-for="(item, i) in state.dataList[state.idx].answersList"
                :key="i"
              >
                <template v-if="state.answerList[state.idx] === 'right'">
                  <span class="icon-check" :class="{'checked': isRightOrWrong(i, 'right')}"></span>
                  <div class="options" :class="{'color-blue': isRightOrWrong(i, 'right')}">{{item}}</div>
                </template>
                <template v-if="state.answerList[state.idx] === 'wrong'">
                  <span class="icon-check" :class="{'fail': isRightOrWrong(i, 'wrong')}"></span>
                  <div class="options" :class="{'color-red': isRightOrWrong(i, 'wrong')}">{{item}}</div>
                </template>
              </div>
            </div>
          </div>
        </div>
        <!-- 答题按钮 -->
        <!-- <div class="exam-answer-btn" v-show="state.showQuestionBtn">
          <van-button type="primary" block color="#5269E6" @click="handleSubmit">选好了，提交我的答案</van-button>
        </div> -->
        <!-- 答题结果 -->
        <div class="exam-answer" v-if="state.dataList[state.idx].answer_flag">
          <p>答案:</p>
          <p>
            正确答案 <span class="color-blue">{{formatAnswer(state.dataList[state.idx].answer_id)}}</span>，
            你的答案 <span class="color-red">{{formatAnswer(state.dataList[state.idx].answer_content)}}</span>。
            <span v-if="state.answerList[state.idx] === 'right'">恭喜你，答对了！</span>
            <span v-else>很遗憾，答错了！</span>
          </p>
        </div>
      </div>
      <!-- 控制按钮 -->
      <div class="exam-btn">
        <div class="flex">
          <div class="exam-btn-cell">
            <van-button type="default" block v-if="state.idx === 0">上一题</van-button>
            <van-button type="primary" block color="#5269E6" v-else  @click="setQuestionIdx(true)">上一题</van-button>
          </div>
          <div class="exam-btn-cell">
            <van-button type="default" block v-if="state.idx + 1 === state.dataList.length">下一题</van-button>
            <van-button type="primary" block color="#5269E6" v-else @click="setQuestionIdx(false)">下一题</van-button>
          </div>
        </div>
      </div>

      <div class="exam-btn" v-if="(state.rightCount + state.wrongCount) === state.dataList.length">
        <van-button type="primary" block color="#5269E6" @click="submit">全部答完，提交本次答题</van-button>
      </div>

      <!-- foot -->
      <div class="exam-foot flex">
        <div class="exam-foot-cell">
          <div class="flex" style="align-items: center;" @click="handleDialog">
            <van-icon name="apps-o" class="foot-icon" size="20" />
            <div style="line-height: 20px;">{{ state.dataList.length > 0 ? state.idx + 1 : 0 }}/{{state.dataList.length}}</div>
          </div>
        </div>
        <div class="flex-row"></div>
        <div class="exam-foot-cell">
          <div class="flex" style="align-items: center;">
            <van-icon name="passed" class="foot-icon right" size="20" /><span class="color-green">{{state.rightCount}}</span>
          </div>
        </div>
        <div class="exam-foot-cell">
          <div class="flex" style="align-items: center;">
            <van-icon name="close" class="foot-icon wrong" size="20"/><span class="color-red">{{state.wrongCount}}</span>
          </div>
        </div>
      </div>

      <!-- 题目序号弹层 -->
      <van-popup v-model:show="state.show" position="bottom" overlay>
        <div class="exam-popup">
          <div class="exam-popup-title flex" style="align-items:center;">
            <!-- <van-icon name="apps-o" class="foot-icon" size="20" />{{idx + 1}}/{{dataList.length}} -->
            <div class="exam-foot-cell">
              <div class="flex" style="align-items: center;" @click="state.show = true">
                <van-icon name="apps-o" class="foot-icon" size="20" />{{ state.dataList.length > 0 ? state.idx + 1 : 0 }}/{{state.dataList.length}}
              </div>
            </div>

            <div class="flex-row"></div>
            <div class="exam-foot-cell">
              <div class="flex" style="align-items: center;">
                <van-icon name="passed" class="foot-icon right" size="20" /><span class="color-green">{{state.rightCount}}</span>
              </div>
            </div>
            <div class="exam-foot-cell">
              <div class="flex" style="align-items: center;">
                <van-icon name="close" class="foot-icon wrong" size="20"/><span class="color-red">{{state.wrongCount}}</span>
              </div>
            </div>
          </div>
          <div class="exam-popup-content">
            <div class="exam-popup-item" v-for="(item, i) in state.answerList.length" :key="i">
              <template v-if="state.answerList[i] === 'right'">
                <div class="icon-circle bg-blue" :class="{'border': state.idx === i}" @click="chooseQuestion(i)">
                  {{i + 1}}
                </div>
              </template>
              <template v-else-if="state.answerList[i] === 'wrong'">
                <div class="icon-circle bg-red" :class="{'border': state.idx === i}" @click="chooseQuestion(i)">
                  {{i + 1}}
                </div>
              </template>
              <template v-else>
                <div class="icon-circle" :class="{'active': state.idx === i}" @click="chooseQuestion(i)">
                  {{i + 1}}
                </div>
              </template>
            </div>
          </div>
        </div>
      </van-popup>

    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getDataList, submitForm } from '@/api'
// import dataList from '@/mock'
import debounce from 'lodash.debounce'
import { timeDifference } from '@/libs/index'
import { Toast } from 'vant'
import { ItemData, AnswerJsonItem } from '@/interface/api'
export default defineComponent({
  name: 'practice-index',
  setup () {
    // const route = useRoute()
    const router = useRouter()
    const state = reactive({
      type: null,
      idx: 0,
      show: false,
      dataList: [] as ItemData[],
      answerList: [] as string[],
      optionTitle: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'G', 'K'], // 字母数组
      rightCount: 0,
      wrongCount: 0,
      startTime: new Date()
    })

    onMounted(() => {
      document.title = 'WIFI教育'
      initData()
    })

    const initData = async () => {
      Toast.loading('加载中')
      try {
        const { data } = await getDataList({
          group: 'h5'
        })
        const dataList = data
        if (dataList && dataList.length > 0) {
          dataList.map((item: ItemData) => {
            item.answer_content = ''
            item.answersList = item.answers.split(',')
            return item
          })
          // 增加一个题目列表数组，存储回答的正确与否
          if (dataList && dataList.length > 0) {
            const answerList = new Array(dataList.length)
            state.answerList = answerList
          }
          state.dataList = dataList
        } else {
          Toast.fail('题库中暂时没有题目')
        }
      } catch (err) {
        Toast.fail({
          message: '网络连接不可用，请稍后重试',
          overlay: true,
          duration: 0
        })
      } finally {
        setTimeout(() => {
          Toast.clear()
        }, 2000)
      }
    }

    // 多选 设置选中项
    const isSelected = (index: number) => {
      const idx = state.idx
      const answerContent = state.dataList[idx].answer_content
      return answerContent.indexOf(index.toString()) > -1
    }

    // 单选和多选 点击选择项
    const chooseOptions = (index: number) => {
      const idx = state.idx
      const type = state.dataList[idx].answer_type
      // // 1单选 2判断 3多选
      if (type === '3') {
        const answerContent = state.dataList[idx].answer_content === '' ? [] : state.dataList[idx].answer_content.split(',')
        const idxNumber = answerContent.indexOf(index.toString())
        if (idxNumber > -1) {
          answerContent.splice(idxNumber, 1)
        } else {
          answerContent.push(index.toString())
        }
        state.dataList[state.idx].answer_content = answerContent.sort((a, b) => Number.parseInt(a) - Number.parseInt(b)).join(',')
      } else {
        state.dataList[idx].answer_content = index.toString()
      }
      // // 显示提交按钮
      state.dataList[state.idx].answer_flag = 'true'
      setAnswerList()
    }

    // 设置答题集合
    const setAnswerList = () => {
      const idx = state.idx
      const type = state.dataList[idx].answer_type
      if (type === '3') {
        const answerId = state.dataList[idx].answer_id
        const answerContent = state.dataList[idx].answer_content
        let temp = 'right'
        if (answerId.length === answerContent.length) {
          for (let i = 0; i < answerId.length; i++) {
            if (!answerId.includes(answerContent[i])) {
              temp = 'wrong'
            }
          }
        } else {
          temp = 'wrong'
        }
        state.answerList[idx] = temp
        if (temp === 'right') {
          state.rightCount = state.rightCount + 1
        } else {
          state.wrongCount = state.wrongCount + 1
        }
      } else {
        const answerId = state.dataList[idx].answer_id
        const answerContent = state.dataList[idx].answer_content.toString()
        state.answerList[idx] = answerId === answerContent ? 'right' : 'wrong'
        if (state.answerList[idx] === 'right') {
          state.rightCount = state.rightCount + 1
        } else {
          state.wrongCount = state.wrongCount + 1
        }
      }
    }

    // 判断答题是否是对的
    const isRightOrWrong = (index: number, type: string) => {
      const idx = state.idx
      const answer = type === 'right' ? state.dataList[idx].answer_id : state.dataList[idx].answer_content
      return answer.indexOf(index.toString()) > -1
    }

    // 格式化答案
    const formatAnswer = (arr: string) => {
      const idx = state.idx
      const type = state.dataList[idx].answer_type
      const optionTitle = state.optionTitle
      if (type === '3') {
        const tempArr = (arr as string).split(',')
        const answerString = tempArr.map((item: any) => {
          return optionTitle[item]
        }).join('、')
        return `【${answerString}】`
      } else {
        return optionTitle[Number.parseInt(arr)]
      }
    }

    // 上一题 true 下一题 false
    const setQuestionIdx = (flag: boolean) => {
      state.idx = flag ? state.idx - 1 : (state.dataList.length > state.idx + 1 ? state.idx + 1 : state.idx)
    }

    // 显示弹层
    const handleDialog = () => {
      state.show = true
    }
    // 弹层 选择题目
    const chooseQuestion = (idx: number) => {
      state.idx = idx
      state.show = false
    }

    // 处理需要上传的答题数据
    const getSubmitanswer = () => {
      const answerJson: AnswerJsonItem[] = []
      state.dataList.forEach((item) => {
        answerJson.push({
          id: item.id,
          answer: item.answer_content
        })
      })
      return JSON.stringify(answerJson)
    }

    const submit = debounce(function () {
      submitAnswer()
    }, 500)

    const submitAnswer = async () => {
      const answer = getSubmitanswer()
      const params = {
        score: state.rightCount * 20,
        answer,
        use_times: timeDifference(state.startTime, new Date())
      }
      Toast.loading('提交中')
      try {
        const { data } = await submitForm(params)
        window.sessionStorage.practice = JSON.stringify({
          rightCount: state.rightCount,
          wrongCount: state.wrongCount,
          count: state.dataList.length,
          remote_auth_server_url: data && data.remote_auth_server_url,
          username: data && data.username,
          password: data && data.password
        })
        router.replace('/success')
      } catch (err) {
        Toast.fail((err as Error).message)
      } finally {
        Toast.clear()
      }
    }

    return {
      state,
      isSelected,
      chooseOptions,
      isRightOrWrong,
      formatAnswer,
      setQuestionIdx,
      handleDialog,
      chooseQuestion,
      submit
    }
  }
})
</script>
<style lang="less" scoped>
.bd {
  padding: 20px;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 120px;
  overflow-y:scroll;
}
.exam-hd {
  line-height: 1.6;
  font-size: 16px;
  text-align: justify;
  &-border {
    color: #5269E6;
    margin-left: 5px;
    margin-right: 5px;
  }
}
.exam-img {
  width: 200px;
  height: 200px;
  margin: 20px auto;
  display: flex;
  align-items: center;
}
.exam-btn {
  position: fixed;
  bottom: 70px;
  left: 0;
  right: 0;
  padding: 0 10px;
}
.exam-btn-cell {
  width: 50%;
  padding: 0 10px;
}
.exam-foot {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 15px 15px;
  // border-top: 1px solid #dcdee0;
  background-color: #f7f8fa;
  color: #646566;
  align-items: center;
  &::after {
    position: absolute;
    box-sizing: border-box;
    content: ' ';
    pointer-events: none;
    right: 0;
    top: 0;
    left: 0;
    border-bottom: 1px solid #ebedf0;
    transform: scaleY(0.5);
  }
  &-cell {
    font-size: 14px;
    line-height: 20px;
    padding-right: 10px;
    &.right {
      text-align: right;
    }
  }
}
.foot-icon {
  color: #5269E6;
  margin-right: 5px;
  line-height: 20px;
  &.right {
    color: #44BB00
  }
  &.wrong {
    color: #FF4444
  }
}
.exam-answer-btn {
  padding: 30px 0px;
}
.exam-answer {
  margin-top: 30px;
  padding: 10px 15px;
  background-color: #f7f8fa;
  line-height: 1.6;
  font-size: 16px;
  color: #646566;
  border-radius: 5px;
  box-shadow: 0 0 5px rgba(0,0,0,0.1);
}
.color-blue {
  color: #5269E6;
}
.color-red {
  color: #FF4444;
}
.color-green {
  color: #44BB00;
}

.icon-check {
  width: 26px;
  height: 26px;
  display: block;
  background-image: url('../../assets/icon-uncheck.png');
  background-repeat: no-repeat;
  background-size: 100% 100%;
  margin-right: 10px;
  &.checked {
    background-image: url('../../assets/icon-checked.png');
  }
  &.fail {
    background-image: url('../../assets/icon-check-fail.png');
  }
}
.options {
  flex:1;
  line-height: 1.4;
}
.exam-popup {
  &-title {
    padding: 10px 15px;
    // border-bottom: 1px solid $gray-4;
    font-size: 14px;
  }
  &-content {
    max-height: 400px;
    background-color: #f7f8fa;
    overflow-y: scroll;
    padding: 10px;
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    .exam-popup-item {
      width: 16.6%;
      height: 32px;
      text-align: center;
      padding: 5px 0;
      display: block;
      .icon-circle {
        width: 32px;
        height: 32px;
        line-height: 32px;
        text-align: center;
        font-size: 14px;
        color: #969799;
        background-color: #fff;
        border-radius: 100%;
        display: inline-block;
        &.active {
          background-color: #f2f3f5;
          border:1px solid #c8c9cc;
        }
        &.bg-blue {
          color: #07C160;
          border:1px solid rgba(222,255,238,1);
          background-color: rgba(222,255,238,1);
          &.border {
            border:1px solid rgba(7,193,96,1);;
          }
        }
        &.bg-red {
          color: #FF4444;
          border:1px solid rgb(253, 226, 226);
          background-color: rgb(253, 226, 226);
          &.border {
            border:1px solid #FF4444;
          }
        }
      }
    }
  }
}
</style>
